package com.microwintech.boardingtreasure.ui.ticketreservation;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Window;
import android.widget.*;
import com.microwintech.boardingtreasure.R;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.TreeSet;

import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.widget.LinearLayout.LayoutParams;
import com.microwintech.boardingtreasure.adapter.ticketreservation.City;
import com.microwintech.boardingtreasure.adapter.ticketreservation.CityAdapter;
import com.microwintech.boardingtreasure.adapter.ticketreservation.SelectCityInterface;
import com.microwintech.boardingtreasure.common.lang.Constant;
import com.microwintech.boardingtreasure.db.dao.CityAirportDao;
import com.microwintech.boardingtreasure.db.entity.CityAirport;
import com.microwintech.boardingtreasure.util.StringUtil;

/**
 * Created by Administrator on 2014/11/6. 热门城市
 */
public class HotCityActivity extends Activity {
	private HashMap<String, Integer> selector;// 存放含有索引字母的位置
	private LinearLayout layoutIndex;
	private ListView listView;
	private TextView tv_show;
	private CityAdapter adapter;
	private String[] indexStr = { "热", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
	// private List<CityAirport> Citys = null;
	// private List<CityAirport> newCitys = new ArrayList<CityAirport>();
	private int height;// 字体高度
	private EditText cityEt;
	private boolean flag = false;
	private int type;
	private Button backBtn;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.hot_city);

		type = getIntent().getIntExtra("type", Constant.ACT_RES_FLIGHT_DYNAMIC_SETOUT_CITY_CODE);
		layoutIndex = (LinearLayout) this.findViewById(R.id.layout);
		cityEt = (EditText) findViewById(R.id.hot_city_search_et);
		cityEt.addTextChangedListener(new CityTextChangedListener());
		layoutIndex.setBackgroundColor(Color.parseColor("#00ffffff"));
		listView = (ListView) findViewById(R.id.listView);
		tv_show = (TextView) findViewById(R.id.tv);
		tv_show.setVisibility(View.GONE);

		backBtn = (Button) findViewById(R.id.hot_city_back_btn);
		backBtn.setOnClickListener(new HotCityOnClick());

		CityAirportDao cityAirportDao = new CityAirportDao(this);
		List<CityAirport> cityAirportList = cityAirportDao.getApplyList();
		refreshData(cityAirportList);
	}

	class HotCityOnClick implements OnClickListener {

		@Override
		public void onClick(View v) {
			finish();
		}

	}

	class SelectCityReal implements SelectCityInterface {

		@Override
		public void selectedCity(CityAirport cityAirport) {
			Intent intent = new Intent();
			intent.putExtra("cityName", cityAirport.getCityName());
			setResult(RESULT_OK, intent);
			finish();
		}
	}

	class CityTextChangedListener implements TextWatcher {

		@Override
		public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {

		}

		@Override
		public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {

		}

		@Override
		public void afterTextChanged(Editable editable) {
			CityAirportDao cityAirportDao = new CityAirportDao(HotCityActivity.this);
			if (StringUtil.isNotBlank(editable.toString())) {
				List<CityAirport> cityAirportList = cityAirportDao.searchApplyListByCondition(editable.toString());
				refreshData(cityAirportList);
			} else {
				List<CityAirport> cityAirportList = cityAirportDao.getApplyList();
				refreshData(cityAirportList);
			}
		}
	}

	private void refreshData(List<CityAirport> cityAirportList) {
		String[] allNames = sortIndex(cityAirportList);
		List<CityAirport> newCitys = sortList(allNames, cityAirportList);
		selector = new HashMap<String, Integer>();
		for (int j = 0; j < indexStr.length; j++) {// 循环字母表，找出newCitys中对应字母的位置
			for (int i = 0; i < newCitys.size(); i++) {
				if (newCitys.get(i).getCityName().equals(indexStr[j])) {
					selector.put(indexStr[j], i);
				}
			}
		}
		adapter = new CityAdapter(this, newCitys, new SelectCityReal());
		adapter.notifyDataSetChanged();
		listView.setAdapter(adapter);

	}

	/**
	 * 重新排序获得一个新的List集合
	 * 
	 * @param allNames
	 */
	private List<CityAirport> sortList(String[] allNames, List<CityAirport> Citys) {
		List<CityAirport> newCitys = new ArrayList<CityAirport>();
		for (int i = 0; i < allNames.length; i++) {
			if (allNames[i].length() != 1) {
				for (int j = 0; j < Citys.size(); j++) {
					if (allNames[i].equals(Citys.get(j).getPinYinName())) {
						CityAirport airport = new CityAirport();
						airport.setCityName(Citys.get(j).getCityName());
						airport.setAirportName(Citys.get(j).getAirportName());
						airport.setPinYinName(Citys.get(j).getPinYinName());
						airport.setThreeLetterCode(Citys.get(j).getThreeLetterCode());
						airport.setWhetherHot(Citys.get(j).getWhetherHot());
						// CityAirport p = new
						// CityAirport(Citys.get(j).getCityName(), Citys
						// .get(j).getPinYinName());
						newCitys.add(airport);
					}
				}
			} else {
				newCitys.add(new CityAirport(allNames[i]));
			}
		}
		return newCitys;
	}

	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		// 在oncreate里面执行下面的代码没反应，因为oncreate里面得到的getHeight=0
		if (!flag) {// 这里为什么要设置个flag进行标记，我这里不先告诉你们，请读者研究，因为这对你们以后的开发有好处
			height = layoutIndex.getMeasuredHeight() / indexStr.length;
			getIndexView();
			flag = true;
		}
	}

	/**
	 * 获取排序后的新数据
	 * 
	 * @param Citys
	 * @return
	 */
	public String[] sortIndex(List<CityAirport> Citys) {
		TreeSet<String> set = new TreeSet<String>();
		// 获取初始化数据源中的首字母，添加到set中
		for (CityAirport City : Citys) {
			set.add(StringHelper.getPinYinHeadChar(City.getCityName()).substring(0, 1));
		}
		// 新数组的长度为原数据加上set的大小
		String[] names = new String[Citys.size() + set.size()];
		int i = 0;
		for (String string : set) {
			names[i] = string;
			i++;
		}
		String[] pinYinNames = new String[Citys.size()];
		for (int j = 0; j < Citys.size(); j++) {
			Citys.get(j).setPinYinName(StringHelper.getPingYin(Citys.get(j).getCityName().toString()));
			pinYinNames[j] = StringHelper.getPingYin(Citys.get(j).getCityName().toString());
		}
		// 将原数据拷贝到新数据中
		System.arraycopy(pinYinNames, 0, names, set.size(), pinYinNames.length);
		// 自动按照首字母排序
		Arrays.sort(names, String.CASE_INSENSITIVE_ORDER);
		return names;
	}

	/**
	 * 绘制索引列表
	 */
	public void getIndexView() {
		LinearLayout.LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, height);
		for (int i = 0; i < indexStr.length; i++) {
			final TextView tv = new TextView(this);
			tv.setLayoutParams(params);
			tv.setText(indexStr[i]);
			tv.setPadding(10, 0, 10, 0);
			layoutIndex.addView(tv);
			layoutIndex.setOnTouchListener(new OnTouchListener() {

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					float y = event.getY();
					int index = (int) (y / height);
					if (index > -1 && index < indexStr.length) {// 防止越界
						String key = indexStr[index];
						if (selector.containsKey(key)) {
							int pos = selector.get(key);
							if (listView.getHeaderViewsCount() > 0) {// 防止ListView有标题栏，本例中没有。
								listView.setSelectionFromTop(pos + listView.getHeaderViewsCount(), 0);
							} else {
								listView.setSelectionFromTop(pos, 0);// 滑动到第一项
							}
							tv_show.setVisibility(View.VISIBLE);
							tv_show.setText(indexStr[index]);
						}
					}
					switch (event.getAction()) {
					case MotionEvent.ACTION_DOWN:
						layoutIndex.setBackgroundColor(Color.parseColor("#606060"));
						break;

					case MotionEvent.ACTION_MOVE:

						break;
					case MotionEvent.ACTION_UP:
						layoutIndex.setBackgroundColor(Color.parseColor("#00ffffff"));
						tv_show.setVisibility(View.GONE);
						break;
					}
					return true;
				}
			});
		}
	}

}